package com.feng.cloud.common.configure;

import com.feng.cloud.common.constants.SystemConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName AsyncThreadPoolTaskExecutorConfigure
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/31 17:09
 * @Version 1.0
 **/
public class AsyncThreadPoolTaskExecutorConfigure {

    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();


    /**
     * 注册异步线程池
     */
    @Bean(SystemConstant.ASYNC_POOL)
    public ThreadPoolTaskExecutor asyncThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int corePoolSize = PROCESSORS <= 1 ? PROCESSORS : PROCESSORS / 2;
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(corePoolSize << 1);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(30);
        executor.setThreadNamePrefix(SystemConstant.ASYNC_POOL_THREAD_NAME_PREFIX);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
